package cn.itsource.service.impl;

import cn.hutool.poi.excel.ExcelUtil;
import cn.itsource.service.IMailService;
import cn.itsource.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
// 发送邮件验证码实现类
@Service
public class MailServiceImpl implements IMailService {
    // 声明发送邮件的工具
    @Autowired
    private JavaMailSender mailSender;

    // 发邮件的邮箱
    @Value("${spring.mail.username}")
    private String from;
    @Override
    public Boolean sendMail(String email) {
        try {
            // 声明邮件主体
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            // 邮件主题
            mailMessage.setSubject("验证码邮件");

            //生成随机数
            String code = randomCode();
            UserContext.setCode(Integer.parseInt(code));

            // 邮件内容
            mailMessage.setText("你收到的验证码是：" + code);
            // 接受邮箱
            mailMessage.setTo(email);
            // 发送邮件的邮箱
            mailMessage.setFrom(from);
            // 发送邮件
            mailSender.send(mailMessage);
            return true;
        }catch (Exception e){
            // 打印异常信息
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    public String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}
